package com.aaa.config;


import com.aaa.entity.User;
import com.aaa.entity.WxUser;
import com.aaa.mapper.WxUserMapper;
import com.aaa.service.MenuService;

import com.aaa.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private MenuService menuService;

    @Resource
    private WxUserMapper wxUserMapper;
    /**
     * 认证
     * */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取的前台username
        JwtToken jwtToken = (JwtToken) authenticationToken;

        String username = (String) jwtToken.getPrincipal();

        if (jwtToken.getLoginType().equals("pc")){
            User sysUser = null;
            try {
                sysUser = menuService.loginname(username);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //判断对象是否有值
            if (sysUser == null) {
                return null;
            }
            //密码不需要我们比对，shiro会给我们比对                      //对象    //获取前台密码
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(sysUser, sysUser.getPwd(), ByteSource.Util.bytes(sysUser.getSalt()), getName());
            return info;
        }else {
            WxUser wxUser = null;
            try {
                wxUser = wxUserMapper.queryByOpenId(username);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //判断对象是否有值
            if (wxUser == null) {
                return null;
            }
            //密码不需要我们比对，shiro会给我们比对                      //对象    //获取前台密码
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(wxUser, "b6ae1d4aa4248f0f98ae43c3d8325b16", ByteSource.Util.bytes("e3d4bf"), getName());
            return info;
        }


    }

    /**
     * 授权
     * */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }


}
